{% extends 'base.html' %}
{% load i18n static simpletags %}
{% block title %}
  上传音频文件
{% endblock %}

{% block load %}
  {% load bootstrap4 %}

  {# Load CSS and JavaScript #}
  {% bootstrap_css %}
  {% bootstrap_javascript jquery='full' %}

  {# Display django.contrib.messages as Bootstrap alerts #}
  {% bootstrap_messages %}
{% endblock %}

{% block content %}
  <!DOCTYPE html>
  <html lang="zh">
    <head>
      <meta charset="UTF-8" />
      <meta name="viewport" content="width=device-width, initial-scale=1.0" />
      <title>上传音频文件</title>
      <script src="https://cdn.tailwindcss.com"></script>
      <script>
        function initFileUpload(dropZone, fileInput) {
          ;['dragenter', 'dragover', 'dragleave', 'drop'].forEach((eventName) => {
            dropZone.addEventListener(eventName, preventDefaults, false)
          })
          function preventDefaults(e) {
            e.preventDefault()
            e.stopPropagation()
          }
          ;['dragenter', 'dragover'].forEach((eventName) => {
            dropZone.addEventListener(eventName, highlight, false)
          })
          ;['dragleave', 'drop'].forEach((eventName) => {
            dropZone.addEventListener(eventName, unhighlight, false)
          })
          function highlight(e) {
            dropZone.classList.add('border-primary')
          }
          function unhighlight(e) {
            dropZone.classList.remove('border-primary')
          }
          dropZone.addEventListener('drop', handleDrop, false)
          function handleDrop(e) {
            const dt = e.dataTransfer
            const files = dt.files
            fileInput.files = files
        
            const fileName = files[0] ? files[0].name : '未选择任何文件'
            const fileNameDisplay = dropZone.querySelector('.file-name')
            if (fileNameDisplay) {
              fileNameDisplay.textContent = fileName
            }
          }
          fileInput.addEventListener('change', function (e) {
            const fileName = e.target.files[0] ? e.target.files[0].name : '未选择任何文件'
            const fileNameDisplay = dropZone.querySelector('.file-name')
            if (fileNameDisplay) {
              fileNameDisplay.textContent = fileName
            }
          })
        }
        window.addEventListener('load', function () {
          const dropZones = document.querySelectorAll('.drop-zone')
          dropZones.forEach((zone) => {
            const input = zone.querySelector('input[type="file"]')
            initFileUpload(zone, input)
          })
        })
      </script>
      <script>
        tailwind.config = {
          theme: {
            extend: {
              colors: {
                primary: '#3B82F6',
                secondary: '#6B7280'
              },
              borderRadius: {
                none: '0px',
                sm: '4px',
                DEFAULT: '8px',
                md: '12px',
                lg: '16px',
                xl: '20px',
                '2xl': '24px',
                '3xl': '32px',
                full: '9999px',
                button: '8px'
              }
            }
          }
        }
      </script>
    </head>
    <body class="min-h-[1024px] bg-gray-50">
      <div class="flex items-center justify-center min-h-screen py-12 px-4 sm:px-6 lg:px-8">
        <div class="w-full max-w-2xl">
          <div class="bg-white shadow-xl rounded-lg p-8 sm:p-12">
            <div class="mb-10">
              <h1 class="text-center text-3xl font-bold text-gray-900">上传音频文件</h1>
            </div>
            <form method="post" enctype="multipart/form-data" class="space-y-8">
              {% csrf_token %}
              <div class="space-y-6">
                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-2">
                    <i class="fas fa-lungs text-gray-500 mr-2"></i>
                    {{ form.cough_file.label|default:'请上传咳嗽音频文件' }}
                  </label>
                  <div class="flex items-center justify-center w-full">
                    <label class="drop-zone flex flex-col w-full h-32 border-2 border-gray-300 border-dashed rounded-lg cursor-pointer bg-gray-50 hover:bg-gray-100">
                      <div class="flex flex-col items-center justify-center pt-4 pb-6">
                        <i class="fas fa-cloud-upload-alt text-2xl text-gray-400 mb-2"></i>
                        <p class="mb-2 text-sm text-gray-500">
                          <span class="font-medium">点击上传</span> 或拖拽文件至此处
                        </p>
                        <p class="text-xs text-gray-500 file-name">未选择任何文件</p>
                      </div>
                      {{ form.cough_file }}
                    </label>
                  </div>
                </div>
                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-2">
                    <i class="fas fa-wind text-gray-500 mr-2"></i>
                    {{ form.breath_file.label|default:'请上传呼吸音频文件' }}
                  </label>
                  <div class="flex items-center justify-center w-full">
                    <label class="drop-zone flex flex-col w-full h-32 border-2 border-gray-300 border-dashed rounded-lg cursor-pointer bg-gray-50 hover:bg-gray-100">
                      <div class="flex flex-col items-center justify-center pt-4 pb-6">
                        <i class="fas fa-cloud-upload-alt text-2xl text-gray-400 mb-2"></i>
                        <p class="mb-2 text-sm text-gray-500">
                          <span class="font-medium">点击上传</span> 或拖拽文件至此处
                        </p>
                        <p class="text-xs text-gray-500 file-name">未选择任何文件</p>
                      </div>
                      {{ form.breath_file }}
                    </label>
                  </div>
                </div>
                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-2">
                    <i class="fas fa-microphone text-gray-500 mr-2"></i>
                    {{ form.speech_file.label|default:'请上传语音音频文件' }}
                  </label>
                  <div class="flex items-center justify-center w-full">
                    <label class="drop-zone flex flex-col w-full h-32 border-2 border-gray-300 border-dashed rounded-lg cursor-pointer bg-gray-50 hover:bg-gray-100">
                      <div class="flex flex-col items-center justify-center pt-4 pb-6">
                        <i class="fas fa-cloud-upload-alt text-2xl text-gray-400 mb-2"></i>
                        <p class="mb-2 text-sm text-gray-500">
                          <span class="font-medium">点击上传</span> 或拖拽文件至此处
                        </p>
                        <p class="text-xs text-gray-500 file-name">未选择任何文件</p>
                      </div>
                      {{ form.speech_file }}
                    </label>
                  </div> 
                </div>
              </div>
              <div class="mt-8">
                <button type="submit" class="w-full !rounded-button bg-primary text-white px-6 py-3 text-base font-medium shadow-sm hover:bg-primary/90 focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2 whitespace-nowrap">提交</button>
              </div>
              <div class="mt-6 flex flex-col items-center space-y-4">
                <a href="{% url 'disease_recognition:history_index' %}" class="text-primary hover:text-primary/80 text-sm font-medium">查看历史记录</a>
                <p class="text-xs text-gray-500">仅允许上传 MP3, WAV 等音频文件</p>
              </div>
            </form>
          </div>
        </div>
      </div>
      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" />
      <style>
        input[type='file'] {
          display: none;
        }
      </style>
    </body>
  </html>

  <script>
    // {{ form.cough_file.id_for_label }} 获取表单字段的 ID ,在封装一层，判断后缀名是否符合要求
    const coughFileInput = document.getElementById('{{ form.cough_file.id_for_label }}')
    const breathFileInput = document.getElementById('{{ form.breath_file.id_for_label }}')
    const speechFileInput = document.getElementById('{{ form.speech_file.id_for_label }}')
    
    function validateFileInput(fileInput) {
      fileInput.addEventListener('change', () => {
        const fileName = fileInput.value
        const allowedExtensions = /(\.mp3|\.wav)$/i // 原理：正则表达式匹配文件名是否以 .mp3 或 .wav 结尾
        if (!allowedExtensions.exec(fileName)) {
          alert('仅允许上传 MP3 或 WAV 文件！')
          fileInput.value = ''
          return false
        }
      })
    }
    
    validateFileInput(coughFileInput)
    validateFileInput(breathFileInput)
    validateFileInput(speechFileInput)
    // 实现必须要三个文件至少有一个上传才能提交
    function validateFileInputNumber(fileInputs) {
      const form = fileInputs[0].closest('form') // form是一个HTMLFormElement对象 closet(‘form') 的'form' 作用是找到最近的form元素
      form.addEventListener('submit', (event) => {
        // event是一个Event对象,具体是什么事件，取决于addEventListener的第一个参数,例如这里是submit事件,传递进来可以获取事件的相关信息,例如阻止默认行为
        let isAnyFileSelected = false
        // 只要有一个文件被选中，则 isAnyFileSelected 为 true
        fileInputs.forEach((input) => {
          if (input.value) {
            isAnyFileSelected = true
          }
        })
        // 否则阻止表单提交
        if (!isAnyFileSelected) {
          event.preventDefault() // event的preventDefault()方法可以阻止表单提交 preventDefault是Event对象的一个方法，用于阻止事件的默认行为
          alert('至少上传一个文件！')
        }
      })
    }
    
    validateFileInputNumber([coughFileInput, breathFileInput, speechFileInput])
  </script>
{% endblock %}
